public  without sharing class Cbl_WorkOrderProductToAssert {

    /**
     * 工单项目->仪器项目
     */
    public static void Cbl_WorkOrderItem2AssetProject(List<WorkOrder__c> list_wo,Map<Id,WorkOrder__c> map_old) {

        for(WorkOrder__c wo:list_wo)
        {
            WorkOrder__c OldWo=map_old.get(wo.Id);
            // 上试剂、外出解决问题
            if(wo.Status__c=='完成' && wo.Status__c!=OldWo.Status__c 
               && 
               (wo.DeveioperName__c == 'Reagents' || wo.DeveioperName__c == 'ProblemSolving'))
            {
                // 工单只会单个单个完成
                if (wo.ServiceManufacture__c != null) {
                    // 找到工单下的工单项目
                    List<WorkOrderItems__c> woiList = [select Id, Name, Items__c,Items__r.Name, WorkOrderBrand__c from WorkOrderItems__c where WorkOrder__c = :wo.Id];
                    // 找到仪器下的仪器项目
                    List<AssetProject__c> apList = [select Id, Name, ProductProject__c, Brand__c from AssetProject__c where Instrument__c = :wo.ServiceManufacture__c];
                    // 用仪器项目里的“项目+品牌”作为map
                    Map<String, String> pbCheck = new Map<String, String>();
                    for (AssetProject__c ap : apList) {
                        pbCheck.put(ap.ProductProject__c + '_' + ap.Brand__c, 'OK');
                    }

                    List<AssetProject__c> newApList = new List<AssetProject__c>();
                    for (WorkOrderItems__c woi : woiList) {
                        String key = woi.Items__c + '_' + woi.WorkOrderBrand__c;
                        // 如果仪器项目里面已经有了相同的“项目+品牌”，工单项目就无视
                        if (pbCheck.containsKey(key)) {
                            continue;
                        }
                        // 新建（如有新的字段需要拷贝在这里添加）
                        else {
                            AssetProject__c newap = new AssetProject__c(
                                Name = woi.Items__r.Name,
                                Instrument__c = wo.ServiceManufacture__c,
                                ProductProject__c = woi.Items__c,
                                Brand__c = woi.WorkOrderBrand__c
                            );

                            newApList.add(newap);
                        }
                    }
                    System.debug('AssetProject==>'+newApList);
                    if (newApList.size() > 0) insert newApList;
                }
            }
        }
    }
    ///其他工单(除安装工单/保养工单/服务工单)点击是否追踪的时候 工单完成 :条件 客户已签字 并且是否追踪不为空
    public static void Cbl_WorkOrderfinish(List<WorkOrder__c> list_wo){
        Set<String> woset = new Set<String>();
        woset.add('InstallationOrder');
        woset.add('NonAgentInstallationOrder');
        woset.add('ServiceOrder');
        woset.add('MaintenanceOrder');

        for(WorkOrder__c wo : list_wo){

            if( !woset.contains(wo.DeveioperName__c) && wo.Signed_UsedDepartmen__c == true && wo.ServiceTracking__c != null ){
                    wo.Status__c = '完成';                
            }
        }
    }
    ///带入安装申请
      public static void Cbl_WorkOrderInstallApply(List<WorkOrder__c> list_wo){
        Map<Id,List<WorkOrder__c>> woSet = new Map<Id,List<WorkOrder__c>>();
        for(WorkOrder__c wo : list_wo){
            if( wo.DeveioperName__c == 'InstallationOrder' || wo.DeveioperName__c =='NonAgentInstallationOrder' ){
                List <WorkOrder__c> woList = new  List <WorkOrder__c>();
                if(woSet.containsKey(wo.Case__c)){
                    woList.addAll(woSet.get(wo.Case__c)) ;
                } 
                woList.add(wo);
                woSet.put(wo.Case__c, woList);
            }
        }
        for(Case c: [select Id ,InstallationApply__c,InstallationApply__r.ReturnedMachine__c from Case where Id in:woSet.keySet()]){

             for (WorkOrder__c wo: woSet.get(c.Id)) {
                wo.WorkOrderInstallApplication__c = c.InstallationApply__c; 
               if(c.InstallationApply__r.ReturnedMachine__c != null ) wo.AssociatedEquipment__c =c.InstallationApply__r.ReturnedMachine__c ; 
            }   
        }


    }
    ///带入工单到安装申请的相关工单
      public static void Cbl_WorkOrderToInstallApply(List<WorkOrder__c> list_wo){
        Set<Id> woset = new Set<Id>();
        for(WorkOrder__c wo : list_wo){
            if( wo.DeveioperName__c == 'InstallationOrder' || wo.DeveioperName__c =='NonAgentInstallationOrder' ){
                   woset.add(wo.Id);
            }
        }
        List<InstallationApply__c>  inaList = new List<InstallationApply__c>();
        Set<Id> tmp = new Set<Id>();

        for(WorkOrder__c wo: [select Id ,Case__r.InstallationApply__c from WorkOrder__c where Id in:woset and status__c= '完成' and Case__r.InstallationApply__c  != null ]){
            InstallationApply__c ia = new InstallationApply__c(Id = wo.Case__r.InstallationApply__c ,
                                                           RelatedWorkOrder__c = wo.Id);

            if(tmp.contains(wo.Case__r.InstallationApply__c))continue; 
            tmp.add(wo.Case__r.InstallationApply__c);
            inaList.add(ia);

        }
        if(inaList.size() > 0) update inaList ;

        
    }

/*
    public static void Cbl_WorkOrderProduct(List<WorkOrder__c> list_wo,Map<Id,WorkOrder__c> map_old)
    {


        //工单关联仪器生成资产
        set<Id> set_woId=new set<Id>();
        Map<String,String>eMap = new Map<String,String>();
        Set <Id> iIds = new Set<Id>();
        for(WorkOrder__c wo:list_wo)
        {
            WorkOrder__c OldWo=map_old.get(wo.Id);
            if(wo.Status__c=='完成' && wo.Status__c!=OldWo.Status__c && wo.DeveioperName__c == 'InstallationOrder' )
            {
                set_woId.add(wo.Id);
                eMap.put(wo.IMEINumber__c,wo.IMEINumber__c + wo.ManufactureInfo__c);
                iIds.add(wo.Technician__c);
            }
        }
        if(set_woId.size() == 0 )return;
        //查询工单对应的个案:
        Map<Id,Id> caseMap = new Map<Id,Id>();
        Map<Id,Id> supplier = new Map<Id,Id>();//供应商
        for(WorkOrder__c w :[select Id, Case__c,Case__r.Dealer__c from WorkOrder__c where Id in: set_woId]){
            caseMap.put(w.Case__c,w.Id);
            supplier.put(w.Id,w.Case__r.Dealer__c);
        }
        //查询安装申请Id
        Map<Id,Id>insId = new Map<Id,Id>();
        for(Case c : [select Id,InstallationApply__c from Case where Id in : caseMap.keySet() ]){
            if(caseMap.containsKey(c.Id) && c.InstallationApply__c != null)insId.put(c.InstallationApply__c,caseMap.get(c.Id));

        }
        //查询安装申请内容
        Map<Id,InstallationApply__c> ins = new Map<Id,InstallationApply__c>();
        for(InstallationApply__c i: [select Id ,ApplicationTraining__c,EquipmentCheck__c,RelatedToReturnMachine__c,
                                     EquipmentCheckGoods__c,SpecialRequirement__c,WarrantyPeriod__c,ChargingStandard__c,ResponseHours__c,
                                     Period__c,CheckPeriod__c,RapidWear__c,CommonAccessories__c,Warranty__c,
                                     ReturnedMachine__c,ReturnedMachine__r.ApplicationTraining__c,ReturnedMachine__r.EquipmentCheck__c,
                                     ReturnedMachine__r.EquipmentCheckGoods__c,InstallationType__c,EnterWay__c,
                                     ReturnedMachine__r.SpecialRequirement__c,ReturnedMachine__r.WarrantyPeriod__c,OpponentSpecialTeam__c,EquipmentType__c,
                                     ReturnedMachine__r.ChargingStandard__c,ReturnedMachine__r.ResponseHours__c,ReturnedMachine__r.Period__c,
                                     ReturnedMachine__r.CheckPeriod__c,ReturnedMachine__r.RapidWear__c,ReturnedMachine__r.CommonAccessories__c,ReturnedMachine__r.Warranty__c
                                     from InstallationApply__c where Id in: insId.keySet()]){
            ins.put(insId.get(i.Id),i);
        }
        //安装人员
        Map<Id,String> installers = new Map<Id,String>();
        for(User u:[select Id,Name from User where Id in:iIds]){
            installers.put(u.Id,u.Name);
        }


        //查询已经存在的仪器
        Map<String ,Equipment__c> exMap = new Map<String,Equipment__c>();
        System.debug('======'+eMap.keySet());
        for(Equipment__c e:[select Id,Account__c,RecordTypeId,IMEINumber__c,EndDate__c,Product__c,Number__c
                            ,FromWorkOrder__c,WhetherStandalone__c,CombinationForm_Ins__c,Type__c,EnterWay__c,
                            ApplicationTraining__c,EquipmentCheck__c,EquipmentCheckGoods__c,SpecialRequirement__c,
                            WarrantyPeriod__c,ChargingStandard__c,ResponseHours__c,Period__c,CheckPeriod__c,
                            RapidWear__c,CommonAccessories__c,DepartmentHeads__c,Installer__c,Software_Version__c,
                            InstrumentVersion__c,Terminal__c,RelatedWorkOrders__c,RelatedInstallationApplication__c,
                            Warranty__c,OpponentSpecialTeam__c,EquipmentType__c
                            from Equipment__c where IMEINumber__c in: eMap.keySet() order by EndDate__c] ){
            exMap.put(e.IMEINumber__c+e.Product__c,e);
        }

 
        RecordType rt=[select id,DeveloperName from RecordType where DeveloperName='AppAssert'];
        List<Equipment__c> list_epInsert=new List<Equipment__c>();
        for(WorkOrder__c wor:list_wo)
        {
            WorkOrder__c OldWo=map_old.get(wor.Id);
            System.debug('Equipment++>'+wor.Status__c + OldWo.Status__c + wor.DeveioperName__c);
            if(wor.Status__c=='完成' && wor.Status__c!=OldWo.Status__c && wor.DeveioperName__c == 'InstallationOrder')
            {
                Equipment__c eq=null;
                InstallationApply__c ia1 = ins.get(wor.Id);

                if(ia1 != null){//如果安装申请不为空
                    if(ia1.InstallationType__c =='升级'){

                        Equipment__c e = new Equipment__c();
                        e.Id = wor.AssociatedEquipment__c;
                        e.Product__c = wor.ManufactureInfo__c;
                        list_epInsert.add(e);

                         continue;
                    }
                   System.debug('==='+ exMap);
                   System.debug('==='+ wor.IMEINumber__c +wor.ManufactureInfo__c);
                   System.debug('==='+exMap.containsKey(wor.IMEINumber__c +wor.ManufactureInfo__c ));
                     if(exMap.containsKey(wor.IMEINumber__c +wor.ManufactureInfo__c )){
                        Equipment__c eqtemp= exMap.get(wor.IMEINumber__c +wor.ManufactureInfo__c);
                        ///如果仪器的关联的客户 == 工单关联的客户 
                        System.debug(eqtemp.Account__c +'===>'+wor.Account__c);
                        if (eqtemp.Account__c == wor.Account__c){
                            eq = eqtemp;
                            // eq.RelatedReturnMachineApplicatio__c = eqtemp.RelatedReturnMachineApplicatio__c;
                        }else{///如果不等则新建仪器 关联退订仪器 
                            eq = new Equipment__c();
                            if(eqtemp.Type__c == '退机' || eqtemp.Type__c == '换机' ){
                                ///关联仪器到新建的仪器里
                                eq.Instrument__c = eqtemp.Id;
                                ///关联退换申请
                            }else{
                                ///异常情况 新建任务通知系统管理员

                                User u = [select Id from User where IsActive=true and   EmployeeNumber =:Label.DuplicatedEquipmentNotiAdmin limit 1];
                                if(u != null){
                                    Task t = new Task(
                                        OwnerId = u.Id,
                                        Subject = '新建仪器重复,请核查！',
                                        Description = '工单:'+wor.Name+'已经存在的仪器：id：' +eqtemp.Id+ '机身号：'+eqtemp.IMEINumber__c+'. 可能原因：退换仪器没有经过退换审批，安装到新的客户下或者仪器机身号为空!请核查！',
                                        WhatId = wor.Id,
                                        Priority = 'normal',
                                        ActivityDate = Date.today()
                                    );

                                    insert t;

                                }

                            }
                        }
                    }else{
                         eq = new Equipment__c();
                         if(ia1.InstallationType__c =='加装'){
                            eq.Instrument__c = wor.AssociatedEquipment__c;
                        }

                    }   

                }else{//如果安装申请为空 判断客户是否为客户记录类型 迈克

                    String deName =  [select Id ,RecordType.DeveloperName from Account where Id =:wor.Account__c].RecordType.DeveloperName;
                    if(deName == 'Maccura'){
                        eq = new Equipment__c();
                    }else{
                        wor.addError('安装工单没有关联安装申请!');
                        break;
                    }
                }
                
                System.debug('==='+eq);

                //eq.Name = wor.ProductManufactureName__c;
                eq.RecordTypeId=rt.Id;
                eq.IMEINumber__c=wor.IMEINumber__c;
                eq.OpponentStatus__c = '安装未使用';
                // eq.OpponentStatus__c = wor.InstrumentUsed__c == null ? null : (wor.InstrumentUsed__c == '是' ? '在用':'未用');
                //if(wor.WhetherToMakeASingle__c != '是')eq.EndDate__c=Date.valueOf(wor.Install_End_Datetime__c);
                if(eq.EndDate__c == null )eq.EndDate__c=wor.InstallData__c;
                eq.Product__c=wor.ManufactureInfo__c;
                eq.Number__c=1;
                eq.WhetherToMakeASingle__c = wor.WhetherToMakeASingle__c;
                eq.FromWorkOrder__c = true;
                eq.WhetherStandalone__c = wor.WhetherStandalone__c;
                eq.CombinationForm_Ins__c = wor.CombinationForm_Ins__c;
                eq.Supplier__c = supplier.get(wor.Id);
                eq.Account__c=wor.Account__c;///客户
                eq.RelatedWorkOrders__c = wor.Id;//关联工单
                eq.Software_Version__c = wor.Software_Version__c;//软件版本
                eq.InstrumentVersion__c = wor.InstrumentVersion__c;//仪器版本
                eq.Terminal__c = wor.Terminal__c; //端子
                eq.OpponentDept__c = wor.UserDepartmen__c;//科室
                eq.DepartmentHeads__c  = wor.UserDepartmentContact__c;//科室负责人
                eq.Installer__c = installers.containsKey(wor.Technician__c)?installers.get(wor.Technician__c):'';//安装人员

                ///将安装申请的服务信息带入到仪器中
                if(ins.containsKey(wor.Id)){
                    InstallationApply__c ia = ins.get(wor.Id);
                    eq.RelatedInstallationApplication__c = ia.Id ;//相关安装申请
                    eq.EnterWay__c = ia.EnterWay__c;
                    if(ia.ReturnedMachine__c == null){

                        if(eq.Instrument__c != null){///换机到其他客户
                            Equipment__c eqtemp= exMap.get(wor.IMEINumber__c +wor.ManufactureInfo__c);

                            //if(ia.RelatedToReturnMachine__c != null)eq.RelatedReturnMachineApplicatio__c = ia.RelatedToReturnMachine__c; ///关联退换安装申请
                            // eq.RelatedReturnMachineApplicatio__c = eqtemp.RelatedReturnMachineApplicatio__c;
                            eq.ApplicationTraining__c = eqtemp.ApplicationTraining__c;//应用培训
                            eq.EquipmentCheck__c = eqtemp.EquipmentCheck__c;//仪器校准
                            eq.EquipmentCheckGoods__c = eqtemp.EquipmentCheckGoods__c;//仪器校准品
                            eq.SpecialRequirement__c = eqtemp.SpecialRequirement__c;//特殊需求
                            eq.WarrantyPeriod__c = eqtemp.WarrantyPeriod__c;//保修年限
                            eq.ChargingStandard__c  = eqtemp.ChargingStandard__c;//保修期满后配件收费标准
                            eq.ResponseHours__c = eqtemp.ResponseHours__c;//响应时间
                            eq.Period__c = eqtemp.Period__c;//维护保养
                            eq.CheckPeriod__c = eqtemp.CheckPeriod__c;//仪器校准周期
                            eq.RapidWear__c = eqtemp.RapidWear__c;//易损件    
                            eq.CommonAccessories__c  = eqtemp.CommonAccessories__c;//常用配件
                            eq.Warranty__c = eqtemp.Warranty__c;//维保项目
                        }else{//新机
                            eq.ApplicationTraining__c = ia.ApplicationTraining__c;//应用培训
                            eq.EquipmentCheck__c = ia.EquipmentCheck__c;//仪器校准
                            eq.EquipmentCheckGoods__c = ia.EquipmentCheckGoods__c;//仪器校准品
                            eq.SpecialRequirement__c = ia.SpecialRequirement__c;//特殊需求
                            eq.WarrantyPeriod__c = ia.WarrantyPeriod__c;//保修年限
                            eq.ChargingStandard__c  = ia.ChargingStandard__c;//保修期满后配件收费标准
                            eq.ResponseHours__c = ia.ResponseHours__c;//响应时间
                            eq.Period__c = ia.Period__c;//维护保养
                            eq.CheckPeriod__c = ia.CheckPeriod__c;//仪器校准周期
                            eq.RapidWear__c = ia.RapidWear__c;//易损件    
                            eq.CommonAccessories__c  = ia.CommonAccessories__c;//常用配件
                            eq.Warranty__c = ia.Warranty__c;//维保项目
                            eq.OpponentSpecialTeam__c = ia.OpponentSpecialTeam__c;
                            eq.EquipmentType__c = ia.EquipmentType__c;
                        }

                    }else{ ///退机
                        eq.ApplicationTraining__c = ia.ReturnedMachine__r.ApplicationTraining__c;//应用培训
                        eq.EquipmentCheck__c = ia.ReturnedMachine__r.EquipmentCheck__c;//仪器校准
                        eq.EquipmentCheckGoods__c = ia.ReturnedMachine__r.EquipmentCheckGoods__c;//仪器校准品
                        eq.SpecialRequirement__c = ia.ReturnedMachine__r.SpecialRequirement__c;//特殊需求
                        eq.WarrantyPeriod__c = ia.ReturnedMachine__r.WarrantyPeriod__c;//保修年限
                        eq.ChargingStandard__c  = ia.ReturnedMachine__r.ChargingStandard__c;//保修期满后配件收费标准
                        eq.ResponseHours__c = ia.ReturnedMachine__r.ResponseHours__c;//响应时间
                        eq.Period__c = ia.ReturnedMachine__r.Period__c;//维护保养
                        eq.CheckPeriod__c = ia.ReturnedMachine__r.CheckPeriod__c;//仪器校准周期
                        eq.RapidWear__c = ia.ReturnedMachine__r.RapidWear__c;//易损件    
                        eq.CommonAccessories__c  = ia.ReturnedMachine__r.CommonAccessories__c;//常用配件

                        eq.Warranty__c = ia.ReturnedMachine__r.Warranty__c;//维保项目
                        eq.Instrument__c = ia.ReturnedMachine__c;//关联仪器

                    }


                }

                list_epInsert.add(eq);

            }


        }

        System.debug('======'+list_epInsert);
        if(list_epInsert.size()>0)upsert list_epInsert;

    }
   
    ////非代理安装工单生成仪器
    public static void Cbl_WorkOrderProduct_NonAgent(List<WorkOrder__c> list_wo,Map<Id,WorkOrder__c> oldMap ){
        //工单关联仪器生成资产
        set<Id> set_woId=new set<Id>();
        Map<String,String>eMap = new Map<String,String>();
        Set <Id> iIds = new Set<Id>();
        for(WorkOrder__c wo:list_wo)
        {   
            WorkOrder__c old = oldMap == null  ||  oldMap.get(wo.Id ) == null ? new WorkOrder__c() : oldMap.get(wo.Id ) ;
            if( wo.DeveioperName__c=='NonAgentInstallationOrder'  && wo.Status__c == '完成' &&  old.Status__c != wo.Status__c )
            {
                set_woId.add(wo.Id);
                eMap.put(wo.IMEINumber__c,wo.IMEINumber__c + wo.ManufactureInfo__c);
                iIds.add(wo.Technician__c);
            }
        }
        if(set_woId.size() == 0 )return;

        //查询工单对应的个案:
        Map<Id,Id> caseMap = new Map<Id,Id>();
        Map<Id,Id> supplier = new Map<Id,Id>();//供应商
        for(WorkOrder__c w :[select Id, Case__c,Case__r.Dealer__c from WorkOrder__c where Id in: set_woId]){
            caseMap.put(w.Case__c,w.Id);
            supplier.put(w.Id,w.Case__r.Dealer__c);
        }
        //查询安装申请Id
        Map<Id,Id>insId = new Map<Id,Id>();
        for(Case c : [select Id,InstallationApply__c from Case where Id in : caseMap.keySet() ]){
            if(caseMap.containsKey(c.Id) && c.InstallationApply__c != null)insId.put(c.InstallationApply__c,caseMap.get(c.Id));

        }
        //查询安装申请内容
        Map<Id,InstallationApply__c> ins = new Map<Id,InstallationApply__c>();
        for(InstallationApply__c i: [select Id ,ApplicationTraining__c,EquipmentCheck__c,EnterWay__c,OpponentSpecialTeam__c,EquipmentType__c,
                                     EquipmentCheckGoods__c,SpecialRequirement__c,WarrantyPeriod__c,ChargingStandard__c,ResponseHours__c,
                                     Period__c,CheckPeriod__c,RapidWear__c,CommonAccessories__c,Warranty__c
                                     from InstallationApply__c where Id in: insId.keySet()]){

            ins.put(insId.get(i.Id),i);
        }
        //安装人员
        Map<Id,String> installers = new Map<Id,String>();
        for(User u:[select Id,Name from User where Id in:iIds]){
            installers.put(u.Id,u.Name);
        }
        //查询已经存在的仪器
        Map<String ,Equipment__c> exMap = new Map<String,Equipment__c>();
        for(Equipment__c e:[select Account__c,RecordTypeId,IMEINumber__c,EndDate__c,Product__c,Number__c
                            ,FromWorkOrder__c,WhetherStandalone__c,CombinationForm_Ins__c,EnterWay__c,
                            ApplicationTraining__c,EquipmentCheck__c,EquipmentCheckGoods__c,SpecialRequirement__c,
                            WarrantyPeriod__c,ChargingStandard__c,ResponseHours__c,Period__c,CheckPeriod__c,
                            RapidWear__c,CommonAccessories__c,DepartmentHeads__c,Installer__c,Software_Version__c,OpponentSpecialTeam__c,EquipmentType__c,
                            InstrumentVersion__c,Terminal__c,RelatedWorkOrders__c,RelatedInstallationApplication__c
                            from Equipment__c where IMEINumber__c in: eMap.keySet()]){
            exMap.put(e.IMEINumber__c+e.Product__c,e);
        }


        RecordType rt=[select id,DeveloperName from RecordType where DeveloperName='AppAssert'];
        List<Equipment__c> list_epInsert=new List<Equipment__c>();
        for(WorkOrder__c wor:list_wo)
        {
            if( wor.DeveioperName__c=='NonAgentInstallationOrder')
            {

                Equipment__c eq=exMap.containsKey(wor.IMEINumber__c +wor.ManufactureInfo__c ) ? exMap.get(wor.IMEINumber__c +wor.ManufactureInfo__c):new Equipment__c();
                //eq.Name = wor.ProductManufactureName__c;
                eq.WhetherToMakeASingle__c = wor.WhetherToMakeASingle__c;
                eq.RecordTypeId=rt.Id;
                eq.IMEINumber__c=wor.IMEINumber__c;
                eq.OpponentStatus__c = '安装未使用';
                //eq.OpponentStatus__c =  wor.InstrumentUsed__c == null ? null : (wor.InstrumentUsed__c == '是' ? '在用':'未用');
                //if(wor.WhetherToMakeASingle__c != '是')eq.EndDate__c=Date.valueOf(wor.Install_End_Datetime__c);
                 if(eq.EndDate__c == null )eq.EndDate__c=wor.InstallData__c;
                eq.Product__c=wor.ManufactureInfo__c;
                eq.Number__c=1;
                eq.FromWorkOrder__c = true;
                eq.WhetherStandalone__c = wor.WhetherStandalone__c;
                eq.CombinationForm_Ins__c = wor.CombinationForm_Ins__c;
                eq.Supplier__c = supplier.get(wor.Id);
                if(eq.Account__c != wor.Account__c)eq.Account__c=wor.Account__c;//如果报错说明是已经存在仪器；
                System.debug('++++'+eq);
                eq.OpponentDept__c = wor.UserDepartmen__c;//科室
                eq.DepartmentHeads__c  = wor.UserDepartmentContact__c;//科室负责人
                eq.Installer__c = installers.containsKey(wor.Technician__c)?installers.get(wor.Technician__c):'';//安装人员
                eq.Software_Version__c = wor.Software_Version__c;//软件版本
                eq.InstrumentVersion__c = wor.InstrumentVersion__c;//仪器版本
                eq.Terminal__c = wor.Terminal__c; //端子
                eq.RelatedWorkOrders__c = wor.Id;//关联工单


                ///将安装申请的服务信息带入到仪器中
                if(ins.containsKey(wor.Id)){
                    InstallationApply__c ia = ins.get(wor.Id);
                     eq.EnterWay__c = ia.EnterWay__c;
                    eq.ApplicationTraining__c = ia.ApplicationTraining__c;//应用培训
                    eq.EquipmentCheck__c = ia.EquipmentCheck__c;//仪器校准
                    eq.EquipmentCheckGoods__c = ia.EquipmentCheckGoods__c;//仪器校准品
                    eq.SpecialRequirement__c = ia.SpecialRequirement__c;//特殊需求
                    eq.WarrantyPeriod__c = ia.WarrantyPeriod__c;//保修年限
                    eq.ChargingStandard__c  = ia.ChargingStandard__c;//保修期满后配件收费标准
                    eq.ResponseHours__c = ia.ResponseHours__c;//响应时间
                    eq.Period__c = ia.Period__c;//维护保养
                    eq.CheckPeriod__c = ia.CheckPeriod__c;//仪器校准周期
                    eq.RapidWear__c = ia.RapidWear__c;//易损件    
                    eq.CommonAccessories__c  = ia.CommonAccessories__c;//常用配件
                    eq.OpponentSpecialTeam__c = ia.OpponentSpecialTeam__c;
                    eq.EquipmentType__c = ia.EquipmentType__c;

                    eq.RelatedInstallationApplication__c = ia.Id ;//相关安装申请
                    eq.Warranty__c = ia.Warranty__c;//维保项目
                }else{
                     String deName =  [select Id ,RecordType.DeveloperName from Account where Id =:wor.Account__c].RecordType.DeveloperName;
                    if(deName == 'Maccura'){
                        
                    }else{
                        wor.addError('安装工单没有关联安装申请!');
                        break;
                    }
                }

                list_epInsert.add(eq);

            }



        }
        System.debug('非代理安装工单'+list_epInsert);
        if(list_epInsert.size() > 0)  upsert list_epInsert;

    }

     */

    public static void Cbl_WorkOrderToassert(List<WorkOrder__c> list_wo,Map<Id,WorkOrder__c> map_old){

        Set<Id> wosets = new Set<Id>();

        Set<Id> rtSets = new Set<Id>{Utils.getRecordTypeIdByDevNameAndObjName('InstallationOrder', 'WorkOrder__c'),Utils.getRecordTypeIdByDevNameAndObjName('NonAgentInstallationOrder', 'WorkOrder__c')} ;
        
        for (WorkOrder__c wo  :list_wo ) {
            
            WorkOrder__c old = map_old.get(wo.Id );
            if(old == null) old = new WorkOrder__c();
            //判断安装工单 并且在完成的时候 
            if(rtSets.contains(wo.RecordTypeId ) && wo.Status__c == '完成' && old.Status__c != wo.Status__c  )wosets.add(wo.Id);
        }

        if(wosets.isEmpty()) return;
        //判断该工单是否已经生成过仪器资产 如果 已经生成过了  则跳过
       for ( Equipment__c eq : [select Id ,RelatedWorkOrders__c  from Equipment__c where RelatedWorkOrders__c in: wosets ]) {
            
            wosets.remove(eq.RelatedWorkOrders__c);
        } 
        if(wosets.isEmpty()) return;


        //仪器的记录类型Id 

        Id equipRTId = Utils.getRecordTypeIdByDevNameAndObjName('AppAssert', 'Equipment__c');
        for (WorkOrder__c wor  : [select Id  ,InstallData__c,IMEINumber__c,Technician__r.Name,
            ManufactureInfo__c,WhetherToMakeASingle__c,WhetherStandalone__c,CombinationForm__c,
            Case__r.InstallationApply__r.NEWDealer__c,Account__c,Software_Version__c,InstrumentVersion__c,
            Terminal__c,UserDepartmen__c,UserDepartmentContact__c,Technician__c,AssociatedEquipment__c,
            AssociatedEquipment__r.ExpiryDate__c,ISE__c,LineType__c,
            Account__r.RecordType.DeveloperName,
            Case__r.TechnicalServicesApplicationNum__c,
            //安装类型
            Case__r.InstallationApply__r.InstallationType__c,
            Case__r.InstallationApply__r.ContractEquipment__r.Opportunity__c,
            //安装申请关联仪器的状态
            Case__r.InstallationApply__r.ReturnedMachine__r.Type__c,
            //关联仪器的保修条款
            Case__r.InstallationApply__r.ReturnedMachine__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.IMEINumber__c ,
            Case__r.InstallationApply__r.ReturnedMachine__r.ApplicationTraining__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.EquipmentCheck__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.EquipmentCheckGoods__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.SpecialRequirement__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.WarrantyPeriod__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.ChargingStandard__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.ResponseHours__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.Period__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.CheckPeriod__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.RapidWear__c,   
            Case__r.InstallationApply__r.ReturnedMachine__r.CommonAccessories__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.Warranty__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.OpponentSpecialTeam__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.EquipmentType__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.ExpiryDate__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.EnterWay__c,
            Case__r.InstallationApply__r.ReturnedMachine__r.ISE__c,
            Case__r.InstallationApply__r.ContractEquipment__c,
            Case__r.InstallationApply__r.OpponentDept__c,

            //安装申请的保修条款
            Case__r.InstallationApply__r.ApplicationTraining__c,
            Case__r.InstallationApply__r.EquipmentCheck__c,
            Case__r.InstallationApply__r.EquipmentCheckGoods__c,
            Case__r.InstallationApply__r.SpecialRequirement__c,
            Case__r.InstallationApply__r.WarrantyPeriod__c,
            Case__r.InstallationApply__r.ChargingStandard__c,
            Case__r.InstallationApply__r.ResponseHours__c,
            Case__r.InstallationApply__r.Period__c,
            Case__r.InstallationApply__r.CheckPeriod__c,
            Case__r.InstallationApply__r.RapidWear__c,   
            Case__r.InstallationApply__r.CommonAccessories__c,
            Case__r.InstallationApply__r.Warranty__c,
            Case__r.InstallationApply__r.OpponentSpecialTeam__c,
            Case__r.InstallationApply__r.EquipmentType__c,
            Case__r.InstallationApply__r.EnterWay__c,

            Case__r.TechnicalServicesApplicationNum__r.i3000__c,
            Case__r.TechnicalServicesApplicationNum__r.OpponentDept__c ,

            //双联机
            (select  Id,MainInstrument__c,InstallDate__c,RelatedInstruments__c ,Code__c  from LineInsWorkOrder__r )


            from WorkOrder__c where Id in:wosets] ) {
      
            //Case__r.InstallationApply__r.InstallationType__c  安装类型
           
           InstallationApply__c ia= wor.Case__r.InstallationApply__r;
            Equipment__c reEq = ia == null ? null : ia.ReturnedMachine__r;

            if(ia == null && wor.Account__r.RecordType.DeveloperName != 'Maccura' && wor.Case__r.TechnicalServicesApplicationNum__c == null ) throw new DmlException('安装工单没有关联安装申请或技术服务申请! ');

            Equipment__c eq =  new Equipment__c();

            Boolean isOldEnsure = false;


            if(wor.Case__r.InstallationApply__r.InstallationType__c  == '新装机' ||  wor.Case__r.InstallationApply__r.InstallationType__c  == '加装'){

               // eq = new Equipment__c();

                // 加装 生成一个新资产 将新的资产 关联到 原来的仪器

            }else if(wor.Case__r.InstallationApply__r.InstallationType__c  == '升级'){ //
                //更换型号
                // eq.Id = ia.ReturnedMachine__c ;
                // eq.Product__c = wor.ManufactureInfo__c;
                // eq.ExpiryDate__c = reEq.ExpiryDate__c;
                // eq.Type__c = '已升级';
                // eq.FromFlow__c = -1 * Math.round(Math.random() * 10) ;
                // eq.RelatedWorkOrders__c = wor.Id;

                // update eq;
                //continue;
                isOldEnsure = true ;


            }else if(wor.Case__r.InstallationApply__r.InstallationType__c  == '同客户更换同型号不同机身号仪器'){
                
               // eq.Id = ia.ReturnedMachine__c;
                
                eq.Product__c = wor.ManufactureInfo__c;
                eq.IMEINumber__c = wor.IMEINumber__c;
                eq.ExpiryDate__c = reEq.ExpiryDate__c;

                 isOldEnsure = true ;

            }else if(wor.Case__r.InstallationApply__r.InstallationType__c  == '同机身号仪器更换客户'){

                if(reEq.IMEINumber__c != wor.IMEINumber__c )throw new DmlException('同仪器换安装客户，机身号必须等于被退机仪器的机身号! ');
                isOldEnsure = true ;

            }else if(wor.Case__r.InstallationApply__r.InstallationType__c  == '双机联机' ||  wor.Case__r.TechnicalServicesApplicationNum__r.i3000__c == '是' ){

                //生成一个新的资产 然后将明细的资产标记为 status__c停用 type__c 已升级 
            

                List<LineInstrument__c> lins = wor.LineInsWorkOrder__r ;
                if(lins == null || lins.size() < 2 ) {

                    throw new DmlException('安装工单没有被联机仪器 或被联机仪器不全! ');
                    //wor.addError();
                }
                if(lins.size() > 2 )throw new DmlException('安装工单被联机仪器超过2台 '); 

                //if(eq.IMEINumber__c == null 

            }

            eq.RecordTypeId= equipRTId ;

            eq.IMEINumber__c=wor.IMEINumber__c;
            eq.OpponentStatus__c = '安装未使用';
            // eq.OpponentStatus__c = wor.InstrumentUsed__c == null ? null : (wor.InstrumentUsed__c == '是' ? '在用':'未用');
            //if(wor.WhetherToMakeASingle__c != '是')eq.EndDate__c=Date.valueOf(wor.Install_End_Datetime__c);
            if(eq.EndDate__c == null )eq.EndDate__c=wor.InstallData__c;
            eq.Product__c=wor.ManufactureInfo__c;
            eq.Number__c=1;
            eq.WhetherToMakeASingle__c = wor.WhetherToMakeASingle__c;
            eq.FromWorkOrder__c = true;
            eq.WhetherStandalone__c = wor.WhetherStandalone__c;
            //eq.CombinationForm_Ins__c = wor.CombinationForm_Ins__c;
            eq.CombinationForm__c = wor.CombinationForm__c;
            eq.Supplier__c = wor.Case__r.InstallationApply__r.NEWDealer__c;
            eq.Account__c=wor.Account__c;///客户
            eq.RelatedWorkOrders__c = wor.Id;//关联工单
            eq.Software_Version__c = wor.Software_Version__c;//软件版本
            eq.InstrumentVersion__c = wor.InstrumentVersion__c;//仪器版本
            eq.Terminal__c = wor.Terminal__c; //端子
            //eq.OpponentDept__c = wor.UserDepartmen__c;//科室
            eq.DepartmentHeads__c  =  wor.UserDepartmentContact__c;//科室负责人
            if(ia != null )eq.OpponentDept__c  = ia.OpponentDept__c;
            if(ia == null)eq.OpponentDept__c  = wor.Case__r.TechnicalServicesApplicationNum__r.OpponentDept__c ; 
            eq.Installer__c = wor.Technician__r.Name ;//安装人员
            eq.ISE__c  = wor.ISE__c;
            

            eq.LineType__c = wor.LineType__c ;

            //保修条款

            // if(ia == null ){
            //     upsert eq;
            //     continue;
            // }
            if(ia != null )eq.Opp__c = ia.ContractEquipment__r.Opportunity__c;
            
            if(ia != null )eq.ContractInstruments__c = ia.ContractEquipment__c;
            if(ia != null )eq.EnterWay__c = ia.EnterWay__c ;
            if(ia != null )eq.RelatedInstallationApplication__c = ia.Id ;
            if(ia != null )eq.ApplicationTraining__c = isOldEnsure  ? reEq.ApplicationTraining__c :ia.ApplicationTraining__c;//应用培训
            if(ia != null )eq.EquipmentCheck__c = isOldEnsure  ? reEq.EquipmentCheck__c : ia.EquipmentCheck__c;//仪器校准
            if(ia != null )eq.EquipmentCheckGoods__c =isOldEnsure  ? reEq.EquipmentCheckGoods__c : ia.EquipmentCheckGoods__c;//仪器校准品
            if(ia != null )eq.SpecialRequirement__c = isOldEnsure  ? reEq.SpecialRequirement__c : ia.SpecialRequirement__c;//特殊需求
            eq.WarrantyPeriod__c =ia == null ? 1 : isOldEnsure  ? reEq.WarrantyPeriod__c :  ia.WarrantyPeriod__c;//保修年限
            if(ia != null )eq.ChargingStandard__c  = isOldEnsure  ? reEq.ChargingStandard__c :  ia.ChargingStandard__c;//保修期满后配件收费标准
            try{
                
                 if(ia != null )eq.ExpiryDate__c = isOldEnsure ?reEq.ExpiryDate__c:  eq.EndDate__c.addYears(Integer.valueOf(eq.WarrantyPeriod__c) );
                 if(ia == null )eq.ExpiryDate__c =eq.EndDate__c.addYears(1);

             }catch(Exception error ){}
            

            if(ia != null )eq.ResponseHours__c = isOldEnsure  ? reEq.ResponseHours__c : ia.ResponseHours__c;//响应时间
            if(ia != null )eq.Period__c = isOldEnsure  ? reEq.Period__c :ia.Period__c;//维护保养
            if(ia != null )eq.CheckPeriod__c =isOldEnsure  ? reEq.CheckPeriod__c :  ia.CheckPeriod__c;//仪器校准周期
            if(ia != null )eq.RapidWear__c = isOldEnsure  ? reEq.RapidWear__c : ia.RapidWear__c;//易损件    
            if(ia != null )eq.CommonAccessories__c  =isOldEnsure  ? reEq.CommonAccessories__c : ia.CommonAccessories__c;//常用配件
            if(ia != null )eq.Warranty__c = isOldEnsure  ? reEq.Warranty__c : ia.Warranty__c;//维保项目
            if(ia != null )eq.OpponentSpecialTeam__c = isOldEnsure  ? reEq.OpponentSpecialTeam__c : ia.OpponentSpecialTeam__c;
            if(ia != null )eq.EquipmentType__c = isOldEnsure  ? reEq.EquipmentType__c : ia.EquipmentType__c;
            

            upsert eq ;

            if(ia != null && ia.ContractEquipment__c != null )ContractCalcEquipmentUtil.installBackToContract(ia.ContractEquipment__c);

            System.debug('Cbl_WorkOrderToassert==>');
             if(wor.Case__r.InstallationApply__r.InstallationType__c  == '加装' || wor.Case__r.InstallationApply__r.InstallationType__c  == '同机身号仪器更换客户' || wor.Case__r.InstallationApply__r.InstallationType__c  == '同客户更换同型号不同机身号仪器' || wor.Case__r.InstallationApply__r.InstallationType__c  == '升级'){

                Equipment__c e =  new Equipment__c(Id=ia.ReturnedMachine__c,Instrument__c=eq.Id,OpponentStatus__c = '使用后停用');

                if(wor.Case__r.InstallationApply__r.InstallationType__c  == '加装')e.Type__c = '已被加装';
                if(wor.Case__r.InstallationApply__r.InstallationType__c  == '升级')e.Type__c = '已升级';
                update e ;
             } 
             if(wor.Case__r.InstallationApply__r.InstallationType__c  == '双机联机'||  wor.Case__r.TechnicalServicesApplicationNum__r.i3000__c == '是'){

                 for (LineInstrument__c lin : wor.LineInsWorkOrder__r  ) {
                    //equipMap.put(lin.RelatedInstruments__c,eq );
                    update new Equipment__c(Id=lin.RelatedInstruments__c,Instrument__c=eq.Id,Type__c = '已联机' );
                   // if(lin.MainInstrument__c)eq.IMEINumber__c = lin.Code__c;
                }
                
             } 


            
        }





    }




}